package com.xuecheng.media.api.controller;

import com.xuecheng.base.model.RestResponse;
import com.xuecheng.media.model.dto.UploadFileParamDto;
import com.xuecheng.media.service.MediaFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Author:王亚栋
 * @Date: 2023/7/21 下午9:09
 * @Version:1.0
 * 上传视频
 */
@Api(value = "大文件上传接口",tags = "大文件上传接口")
@RestController
public class BigFilesController {

    @Autowired
    private MediaFileService mediaFileService;

    @ApiOperation("文件上传前对文件进行检查")
    @PostMapping("/upload/checkfile")
    public RestResponse<Boolean> checkFile(@RequestParam("fileMd5") String fileMd5){


        return mediaFileService.checkFile(fileMd5);
    }

    @ApiOperation("分块文件上传前的检测")
    @PostMapping("/upload/checkchunk")
    public RestResponse<Boolean> checkChunkFile(@RequestParam("fileMd5") String fileMd5,
                                                @RequestParam("chunk") int chunk){

        return mediaFileService.checkChunk(fileMd5,chunk);
    }

    @ApiOperation("上传分块文件")
    @PostMapping("/upload/uploadchunk")
    public RestResponse uploadChunk(@RequestParam("fileMd5") String fileMd5,
                                     @RequestParam("file") MultipartFile file,
                                     @RequestParam("chunk") int chunk) throws IOException {

        //创建一个临时文件
        File tempFile = File.createTempFile("minio", ".temp");

        file.transferTo(tempFile);

        //文件路径
        String localFilePath = tempFile.getAbsolutePath();

        return mediaFileService.uploadChunk(fileMd5,chunk,localFilePath);
    }

    @ApiOperation("合并文件")
    @PostMapping("/upload/mergechunks")
    public RestResponse mergeChunks(@RequestParam("fileMd5") String fileMd5,
                                    @RequestParam("fileName") String fileName,
                                    @RequestParam("chunkTotal") int chunkTotal){

        Long companyId = 1232141425L;

        //文件信息对象
        UploadFileParamDto uploadFileParamDto = new UploadFileParamDto();
        uploadFileParamDto.setFilename(fileName);
        uploadFileParamDto.setTags("视频文件");
        uploadFileParamDto.setFileType("001002");

        RestResponse restResponse = mediaFileService.mergeChunks(companyId, fileMd5, chunkTotal, uploadFileParamDto);

        return restResponse;
    }
}
